#!/usr/bin/env bash

export AWS_DEFAULT_REGION="cn-northwest-1"
export MAVEN_CENTRAL="https://maven.aliyun.com/repository/central"
export LOGBACK_HOST="172.19.250.99"

#/usr/bin/dnf -y --setopt install_weak_deps=False install unzip tar rsync java-17-openjdk-headless
#/usr/bin/dnf -y install unzip tar java-17-openjdk-headless

# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-categories.html
SESSION_TOKEN=$(curl -s -XPUT -H'X-aws-ec2-metadata-token-ttl-seconds: 21600' http://169.254.169.254/latest/api/token)
INSTANCE_ID=$(curl -s -H"X-aws-ec2-metadata-token: ${SESSION_TOKEN}" http://169.254.169.254/latest/meta-data/instance-id)
#APP=$(curl -s -H"X-aws-ec2-metadata-token: ${SESSION_TOKEN}" http://169.254.169.254/latest/meta-data/tags/instance/Application)
APP='lake'
MODULE=$(curl -s -H"X-aws-ec2-metadata-token: ${SESSION_TOKEN}" http://169.254.169.254/latest/meta-data/tags/instance/Module)

PROFILE_TAG_STATUS=$(curl -s --head -w '%{http_code}' -o /dev/null -H"X-aws-ec2-metadata-token: ${SESSION_TOKEN}" http://169.254.169.254/latest/meta-data/tags/instance/Profile)
if [ ${PROFILE_TAG_STATUS} -lt 300 -a ${PROFILE_TAG_STATUS} -ge 200 ]; then
	PROFILE=$(curl -s -H"X-aws-ec2-metadata-token: ${SESSION_TOKEN}" http://169.254.169.254/latest/meta-data/tags/instance/Profile)
else
	PROFILE="master"
fi
unset PROFILE_TAG_STATUS

USER="${MODULE}"
SERVICE="${MODULE}"

GROUP_ID="com.lakeworks"
ARTIFACT_ID="lakeworks-admin"

GROUP_PATH=$(echo "${GROUP_ID}" | /usr/bin/sed 's/\./\//g')

REPO_BUCKET="repo.dajingxiapp.com"
REPO_URL="s3://${REPO_BUCKET}/releases/${GROUP_PATH}"

############################ BEGIN awscli ####################################
#ZIP=$(mktemp --suffix=.zip)
#curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "${ZIP}"
#unzip -q "${ZIP}"
#aws/install
#rm -rf ${ZIP} aws
#unset ZIP

AWS="$(which aws) --no-cli-pager --no-paginate --region ${AWS_DEFAULT_REGION} --color off"
############################ END awscli ####################################

############################ BEGIN user/group ####################################
useradd -m -G systemd-journal ${USER}

USER_HOME=$(getent passwd "${USER}" | cut -d: -f6)

mkdir ${USER_HOME}/.ssh
$AWS s3 cp s3://deploy.dajingxiapp.com/authorized_keys ${USER_HOME}/.ssh/
chmod -R go-rwx ${USER_HOME}/.ssh
chown -R ${USER}:${USER} ${USER_HOME}/.ssh
############################ END user/group ####################################

TARGET_DIR=${USER_HOME}/${ARTIFACT_ID}

############################ BEGIN service unit file ####################################
mkdir -vp ${USER_HOME}/.config/systemd/user/default.target.wants

echo '[Unit]
Description='${APP}'-'${MODULE}'-'${PROFILE}'
After=network-online.target

[Service]
Type=simple
PrivateTmp=yes

Environment="TZ=Asia/Shanghai"
Environment="LANG=en_US.UTF-8"

Environment="SPRING_PROFILES_ACTIVE=druid,'${PROFILE}'"

Environment="LOGBACK_CONTEXT='${APP}'-'${MODULE}'-'${PROFILE}'.'${INSTANCE_ID}'"
Environment="LOGBACK_HOST='${LOGBACK_HOST}'"
Environment="LOGBACK_PORT=4560"

Environment=CLASSPATH='${TARGET_DIR}'/libs/*
Environment=JDK_JAVA_OPTIONS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai -Duser.language=en -Duser.country=US -XX:-OmitStackTraceInFastThrow -Xms2G -Xmx2G -Xlog:gc*"

ExecStartPre='${AWS}' s3 cp s3://deploy.dajingxiapp.com/'${APP}'/'${MODULE}'/'${PROFILE}'.yml '${USER_HOME}'/application-'${PROFILE}'.yml
ExecStart=/usr/bin/java com.lakeworks.LakeWorksApplication

UMask=0077
SuccessExitStatus=143

[Install]
WantedBy=default.target' > "${USER_HOME}/.config/systemd/user/${SERVICE}.service"

ln -svrt ${USER_HOME}/.config/systemd/user/default.target.wants ${USER_HOME}/.config/systemd/user/${SERVICE}.service
chown -R ${USER}:${USER} ${USER_HOME}/.config
############################ END service unit file ####################################

############################# BEGIN deploy ####################################
VER_TAG_STATUS=$(curl -s --head -w '%{http_code}' -o /dev/null http://169.254.169.254/latest/meta-data/tags/instance/Version)
if [ ${VER_TAG_STATUS} -lt 300 -a ${VER_TAG_STATUS} -ge 200 ]; then
	VERSION=$(curl -s http://169.254.169.254/latest/meta-data/tags/instance/Version)
else
	VERSION=$($AWS s3 cp ${REPO_URL}/${ARTIFACT_ID}/maven-metadata.xml - | xmllint --xpath '/metadata/versioning/release/text()' -)
fi
unset VER_TAG_STATUS

echo "Releasing ${GROUP_ID}:${ARTIFACT_ID}@${VERSION}"

TAR=${ARTIFACT_ID}-${VERSION}.tar.gz

mkdir -p ${TARGET_DIR}
$AWS s3 cp ${REPO_URL}/${ARTIFACT_ID}/${VERSION}/${TAR} - | tar vzx -C ${TARGET_DIR}
chown -R ${USER}:${USER} ${TARGET_DIR}
############################# END deploy ####################################

$AWS ec2 create-tags --resources ${INSTANCE_ID} --tags Key=Name,Value=${APP}-${MODULE}-${PROFILE}-${VERSION} Key=Profile,Value=${PROFILE} Key=Version,Value=${VERSION}

loginctl enable-linger ${USER}

#TARGET_GROUP_ARN=$($AWS --output text elbv2 describe-target-groups --names "${APP}-${MODULE}-${PROFILE}" --query 'TargetGroups[0].TargetGroupArn')
##TARGET_GROUP_ARN=$($AWS --output text resourcegroupstaggingapi get-resources --resource-type-filters elasticloadbalancing:targetgroup --tag-filters Key=Application,Values=${APP} Key=Module,Values=${MODULE} Key=Profile,Values=${PROFILE} --query ResourceTagMappingList[0].ResourceARN)
#if [ -n "${TARGET_GROUP_ARN}" ]; then
#	$AWS elbv2 register-targets --target-group-arn ${TARGET_GROUP_ARN} --targets Id=${INSTANCE_ID}
#fi
